package com.zpq.jspTemplate;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.BodyTagSupport;

/**
 * 模版 tag 
 *
 */
public class TemplateTag extends BodyTagSupport {
    
    private static final long serialVersionUID = 1L;
    private String uri;
    private Map<String, Object> overrideMap;
    
    @Override
    public int doStartTag() throws JspException {
        overrideMap = getOverrideMap();
        
        return EVAL_BODY_INCLUDE;
    }
    
    @SuppressWarnings("unchecked")
    private Map<String, Object> getOverrideMap() {
        overrideMap = (Map<String, Object>) pageContext.getAttribute(Utils.getTemplateParamName("overrideMap"), PageContext.REQUEST_SCOPE);
        if (overrideMap == null) {
            overrideMap = new HashMap<String, Object>();
            pageContext.setAttribute(Utils.getTemplateParamName("overrideMap"), overrideMap, PageContext.REQUEST_SCOPE);
        }
        return overrideMap;
    }

    @Override
    public int doEndTag() throws JspException {
       
        try {
            pageContext.include(uri);
        } catch (ServletException e) {
            throw new JspException(e);
        } catch (IOException e) {
            throw new JspException(e);
        }
        
        if (overrideMap.size() > 0) {
            StringBuilder sb = new StringBuilder(50);
            sb.append("[");
            for (Iterator<String> iterator = overrideMap.keySet().iterator(); iterator.hasNext();) {
                String blockName = (String) iterator.next();
                sb.append(blockName.substring(Utils.TEMPLATE_PRIFIX_LENGTH)+" ");
            }
            sb.append("]");
            throw new JspException("page "+sb.toString() + " does not contain in template " + uri);
        }
        return EVAL_PAGE;
    }
    
    @Override
    public void release() {
        super.release();
        overrideMap.clear();
    }
    
    public String getUri() {
        return uri;
    }
    public void setUri(String uri) {
        this.uri = uri;
    }
}
